<template>
    <div v-if="detailInfo">
        <van-nav-bar title="详情" />    
        <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
            <van-swipe-item v-for="(img, index) in [detailInfo.img1, detailInfo.img2, detailInfo.img3, detailInfo.img4]"
                :key="index">
                <img class="img" :src="img" alt="">
            </van-swipe-item>
        </van-swipe>
        <van-row class="row desc">
            {{ detailInfo.proname }}
        </van-row>
        <van-row class="row price">
            {{ (detailInfo.originprice * detailInfo.discount) / 10 }}
        </van-row>

        <van-action-bar>
            <van-action-bar-icon icon="chat-o" text="客服" dot />
            <van-action-bar-icon icon="cart-o" text="购物车" badge="5" />
            <van-action-bar-icon icon="shop-o" text="店铺" badge="12" />
            <van-action-bar-button type="warning" text="加入购物车" @click="addToShoppingCar" />
            <van-action-bar-button type="danger" text="立即购买" />
        </van-action-bar>
    </div>
</template>

<script setup>
import { ref, watchEffect } from "vue";
import { storeToRefs } from "pinia";
import { useRouter, useRoute } from 'vue-router';
import { showFailToast, showSuccessToast, showToast } from 'vant';

import { getDetailAPI } from "@/api/pro.js";
import { addCartAPI } from "@/api/cart.js";
import { useUserStore } from "@/stores/user.js"

let router = useRouter();
let route = useRoute();
let User = useUserStore();

let proid = ref(route.query.proid);
let detailInfo = ref(null);
let { isLogin, userid } = storeToRefs(User);

let getDetail = async () => {
    try {
        var res = await getDetailAPI({ proid: proid.value });
        console.log("商品详情", res);
        detailInfo.value = res.data;
    } catch (err) {
        showFailToast(err.message);
    }
}

let addToShoppingCar = async () => {
    // 加入购物车
    // 1. 判断用户是否登录   
    // a. 没有登录 => 去登录, 成功之后再回来
    // b. 已经登录 => 直接买
    console.log("isLogin", isLogin.value);
    if (isLogin.value) {
        console.log("买!!!",userid);
        try {
            var res = await addCartAPI({
                userid: userid.value,
                proid: proid.value,
                num: 1,
            })
            showSuccessToast("加入成功");
            router.push({name:"car"})
        } catch (err) {
            showFailToast(err.message);
        }
    } else {
        router.replace({ name: "login", query: { ReturnUrl: encodeURIComponent(route.fullPath) } })
    }
}

watchEffect(() => {
    console.log(1111);
    getDetail();
})









</script>

<style lang="scss" scoped>
.my-swipe {
    img {
        width: 60%;
        display: block;
        margin: 0 auto;
    }
}

.row {
    padding: 0 0.1rem;
}
</style>